package com.wx.house.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author ：罗棋
 * @Email ：58428467@qq.com
 * @date ：Created in 2019/5/22 11:24
 * @description： jwt授权和鉴权
 * @version: ：V1.0.0
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class JwtUtils {
    @Builder.Default
    private String TokenHeader = "authorization";
    @Builder.Default
    private String Secret = "aaa";
    @Builder.Default
    private String ISS = "稳信科技";

    //15个小时
    @Builder.Default
    private long EXPIRATION = 54000L;

    //半个月免登陆
    @Builder.Default
    private long EXPIRATION_REMEMBER = 1296000L;

    @Builder.Default
    private long REAL_EXPIRATION = 0L;

    /**
     * @Description 最多16个参数
     */
    private Map<String, String> paramList = new HashMap<>(16);
    private String token;
    private String username;
    @Builder.Default
    private boolean isRemember = false;


    public String token() {
        long expiration = this.isRemember ? EXPIRATION_REMEMBER : EXPIRATION;
        System.err.println("是否记住密码:" + isRemember);
        System.err.println("token有效期:" + expiration);
        JwtBuilder jwts = Jwts.builder();
        jwts.signWith(SignatureAlgorithm.HS512, this.Secret.getBytes())
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000));

        //加入参数列表
        paramList.forEach(jwts::claim);
        paramList.forEach((k, v) -> System.err.println("key:" + k + "     value:" + v));
        this.token = jwts.compact();
        REAL_EXPIRATION = expiration;
        return jwts.compact();
    }

    public Long exp() {
        return this.REAL_EXPIRATION;
    }

    public Claims claims() {
        return Jwts.parser().setSigningKey(Secret.getBytes())
                .parseClaimsJws(this.token)
                .getBody();

    }

    public String userName() {
        return this.claims().getSubject();
    }

    public String die() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims().getExpiration());
    }

}
